<template>
  <div class="msg-talk">
      <a href="#/" class="ico-home"></a>
        <ul class="talk-list clearFix">
              <li :class="{'left':chat.customer_id != id,'right':chat.customer_id == id}" v-for="chat in strArr">
                  <!--<div class="time-box"><span class="time">{{chat.date_add}}</span></div>-->
                  <div class="clearFix ">
                      <img class="icon" width="40" height="40" :src="chat.avatar" v-if="chat.customer_id != id"
                           @click="gotoAddress({path:'/otherIndex?id='+otherid})"
                      >
                      <img class="icon" width="40" height="40" :src="'http://api.piver.cn/image/users/'+id+'.jpg'" v-if="chat.customer_id == id"
                           @click="gotoAddress({path:'/otherIndex?id='+id})"
                      >
                      <p class="text">
                          	{{chat.content}}
                      </p>
                  </div>
              </li>
              <!--<li class="right">
                  <div class="time-box"><span class="time">2017-01-03 20:43</span></div>

                  <div class="clearFix ">
                      <img class="icon" src="https://dummyimage.com/40x40">
                      <p class="text">
                          您好，
                      </p>
                  </div>
              </li>-->
        </ul>

        <div class="pinglun-box">
          <div class="pl-txt">
            <input type="text" v-model="iptMsg" @keyup.13="sendMsg(iptMsg)">
            <mt-button type="danger" @click="sendMsg(iptMsg)" >发送</mt-button>
          </div>
        </div>
  </div>
</template>

<script>
import {Toast} from 'mint-ui'
export default {
  name: 'MsgTalk',
  data () {
    return {
    	config: {
				host: '123.206.31.94',
				port: '9501',
				initUserUrl: '11',
				getUserHistoryMsgUrl: '222',
			},
			id: JSON.parse(sessionStorage.user).customer_id || '',
      otherid:this.$route.query.id,
      token:sessionStorage.user && JSON.parse(sessionStorage.user).token || '',
      iptMsg: '',
      closeFlag: false,

      strArr: [
			      {
			      	'customer_id':'default',
			      	'avatar':'http://api.piver.cn/image/users/'+this.$route.query.id+'.jpg',
			      	'content': '您好，有什么可以帮助您的么？'
			      }
      ]
//    ws: ''
    }
  },
  methods: {
    gotoAddress(path){
      this.$router.push(path)
    },
  	sendMsg (iptMsg) {
  		if(!utilities.isNull(iptMsg)){
  			let Message = {
	      	content: this.iptMsg,
					to_customer_id: this.$route.query.id,
					token: this.token
        }
  			if(this.GLOBAL.ws.readyState == 3){
  				this.ajaxMessage(Message);
  			}else if (this.GLOBAL.ws.readyState == 1) {
  				this.GLOBAL.ws.send(JSON.stringify(Message));
				}
	  		this.strArr.push({'content':this.iptMsg,'customer_id':this.id,'avatar':'http://api.piver.cn/image/users/'+this.id+'.jpg'});
	  		this.iptMsg = '';
  		}else{
  			Toast('发送内容不能为空');
  		}

  	},
  	ajaxMessage (Message) {
//		alert('ajaxmessage')
  		var _this = this;
	      var ajaxData1 = {};
	      ajaxData1.token = Message.token;
	      ajaxData1.receive_id = this.otherid;
	      ajaxData1.content = Message.content;
	      $.ajax({
	        type:'post',
	        url: RouteMap.messageTalk,
	        data:ajaxData1,
	        success:function(res){
	          if(res.code == 200){
	            console.log(res.data);
	          }
	          else{
	            Toast(res.msg)
	          }
	        }
	      })
  	},
  	clientOnMsg () {
  		//监听收到的信息

			let _this = this;
			this.GLOBAL.ws.onmessage = function(evt) {
				var received = evt.data;
				var received_msg = eval("("+received+")");
				for(let i=0; i<received_msg.length; i++) {
					_this.strArr.push(received_msg[i]);
				}
        console.log(_this.strArr);
			};
  	},
  	_chatInit () {
  		let _this = this;
  		clearInterval(_this.GLOBAL.globalMessageTimer);
  		this.GLOBAL.ws.close && this.GLOBAL.ws.close();
//			token : 4a7c75c77ac267c4130a720232d58ce7 -> 对应用户ID:12
//			token : 3f826dbfb943c6436e2f2ea3c565a281 -> 对应用户ID:22
//			clearInterval(_this.msgInterval)
			this.GLOBAL.ws = new WebSocket('ws://' + this.config.host + ':' + this.config.port + '?token=' + this.token + '&touid=' + this.$route.query.id);
  		console.log(this.GLOBAL.ws.close)
  		this.GLOBAL.ws.onopen = function(event) {
				console.info("已连接到服务器!");
			}
			//关闭服务器
			this.GLOBAL.ws.onclose = function(event) {
				this.closeFlag = true;
				clearInterval(_this.GLOBAL.globalMessageTimer);
				console.log('服务器已经关闭!',event);
			};
			this.clientOnMsg ();
			//初始化生成用户登陆数据
			_this.GLOBAL.globalMessageTimer = setInterval(function(){
					var heartMessage = {
						'heartbeat':1,
						'to_customer_id':_this.$route.query.id,
						'token': _this.token
					}
					if(_this.GLOBAL.ws.readyState != 3){
						_this.GLOBAL.ws.send(JSON.stringify(heartMessage));
					}else{
						clearInterval(_this.GLOBAL.globalMessageTimer);
					}

			},1000);
  	},
  },
  created() {
  	
  	this._chatInit()
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.right{
	float: right;
}
.msg-talk{
	position: absolute;
	left: 0;
	right: 0;
	top: 0;
	bottom: 2.5rem;
	overflow: auto;
  padding:.4rem;
  background:#fff;
  font-size: 0.6rem;
}
.msg-talk ul li{
width: 100%;
/*margin-top:.7rem;*/
}
.msg-talk ul li .clearFix{
margin:.4rem 0;
}
.time-box{
  text-align: center;
}
.msg-talk ul li .time{
  background:#c2c2c2;
  color: #fff;
  display: inline-block;
  padding: 0 0.8rem;
  border-radius: 1rem;
  font-size: 0.5rem;

}
.msg-talk ul li .icon{
    border-radius:50%;
}
.msg-talk ul li .text{
  max-width:60%;
  line-height:1rem;
  padding:.2rem .3rem;
  margin:0.1rem 0.3rem;
  border-radius:0.3rem ;
  display: inline-block;
}

.msg-talk ul li.left .icon{
  float:left;
}
.msg-talk ul li.left .text{
   float:left;
   background:#f5f5f5;
}

.msg-talk ul li.right .icon{
  float:right;
}
.msg-talk ul li.right .text{
  float:right;
  background:#c04c50;
  color: #fff;

}
.talk-list{
  padding-bottom: 3rem;
}
  .produce-font{
    line-height: .8rem;
  }
  .msg-talk ul li .img-text{
    padding: 0.3rem;
  }
  .pro-img{
    margin-right: 0.3rem;
  }
  .pinglun-box{
    background: #fff;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    border-top: 1px solid #eee;
    padding:0.5rem ;
  }

  .pinglun-box input{
    border: 1px solid #707070;
    padding: 0.2rem 0.5rem;
    border-radius: .5rem;
    width: 10.8rem;
  }
  .pinglun-box input,.pinglun-box button{
    vertical-align: middle;
  }
.pinglun-box button{
  width: 3rem;
}
</style>
